import {
  createRouter,
  createWebHistory
  // createWebHashHistory
} from 'vue-router'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
// createRouter 创建路由实例
//1. history模式 createWebHistory  地址栏不带#
//2. hash模式 createWebHashHistory 地址栏带#
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/login/loginPage.vue') },
    {
      path: '/',
      component: () => import('@/views/layout/LayoutContainer.vue'),
      redirect: '/article/manage',
      children: [
        {
          path: '/article/manage',
          component: () => import('@/views/article/ArticleManage.vue')
        },
        {
          path: '/article/channel',
          component: () => import('@/views/article/ArticleChannel.vue')
        },
        {
          path: '/user/profile',
          component: () => import('@/views/user/UserProfile.vue')
        },
        {
          path: '/user/password',
          component: () => import('@/views/user/UserPassword.vue')
        },
        {
          path: '/user/avatar',
          component: () => import('@/views/user/UserAvatar.vue')
        }
      ]
    }
  ]
})
// 登录访问拦截 =>默认是直接放行的
// 根据返回值决定是放行还是拦截
// 返回值
// 1.undefined / true 直接放行
// 2.false拦回from的地址页面
// 3.具体路径或者路径对象 拦截到对应的地址
router.beforeEach((to) => {
  // 如果没有token，且访问的是非登录页，拦截到正常登录
  const userStore = useUserStore()
  if (!userStore.token && to.path !== '/login') {
    ElMessage.error('请先登录')
    return '/login'
  }
})
export default router
